<template>
    <PageLayout>
        <!-- 页面头部 -->
        <section class="py-12 bg-gradient-to-r from-primary/5 to-secondary/5">
            <div class="container mx-auto px-4 text-center">
                <SectionTitle 
                    title="美好文字" 
                    subtitle="收集那些触动心灵的句子，让文字的力量温暖每一个平凡的日子" 
                />
            </div>
        </section>

        <!-- 筛选和搜索 -->
        <section class="py-6 bg-white/80 backdrop-blur-sm sticky top-0 z-30 border-b border-neutral-200">
            <div class="container mx-auto px-4">
                <div class="flex flex-col md:flex-row gap-4 items-center justify-between">
                    <!-- 主题筛选 -->
                    <div class="flex gap-2 flex-wrap">
                        <button v-for="theme in themes" :key="theme.value" @click="selectedTheme = theme.value" :class="[
                            'px-4 py-2 rounded-full text-sm transition-colors',
                            selectedTheme === theme.value
                                ? 'bg-primary text-white'
                                : 'bg-neutral-100 text-neutral-600 hover:bg-neutral-200'
                        ]">
                            {{ theme.label }}
                        </button>
                    </div>

                    <!-- 搜索框 -->
                    <div class="relative">
                        <input v-model="searchQuery" type="text" placeholder="搜索文字..."
                            class="pl-10 pr-4 py-2 border border-neutral-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                        <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-400"></i>
                    </div>
                </div>
            </div>
        </section>

        <!-- 文字网格 -->
        <section class="py-12">
            <div class="container mx-auto px-4">
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    <div v-for="quote in filteredQuotes" :key="quote.id" @click="openQuoteDetail(quote)" class="cursor-pointer">
                        <QuoteCard :quote="quote" />
                    </div>
                </div>

                <!-- 加载更多 -->
                <div class="text-center mt-12" v-if="hasMore">
                    <button @click="loadMore" :disabled="loading"
                        class="bg-primary hover:bg-primary/90 text-white px-8 py-3 rounded-lg transition-colors disabled:opacity-50">
                        {{ loading ? '加载中...' : '加载更多' }}
                    </button>
                </div>
            </div>
        </section>

        <!-- 文字详情弹窗 -->
        <div v-if="selectedQuote" class="fixed inset-0 bg-black/80 z-50 flex items-center justify-center p-4"
            @click="closeQuoteDetail">
            <div class="bg-white rounded-2xl max-w-2xl w-full p-8 relative" @click.stop>
                <button @click="closeQuoteDetail"
                    class="absolute top-4 right-4 w-8 h-8 bg-neutral-100 text-neutral-600 rounded-full flex items-center justify-center hover:bg-neutral-200 transition-colors">
                    <i class="fa fa-times"></i>
                </button>

                <div class="text-center">
                    <div class="mb-6">
                        <i class="fa fa-quote-left text-4xl text-primary/30"></i>
                    </div>
                    <blockquote class="text-xl text-neutral-700 mb-6 leading-relaxed font-serif">
                        {{ selectedQuote.text }}
                    </blockquote>
                    <cite class="text-neutral-600 not-italic">— {{ selectedQuote.author }}</cite>
                    <div class="mt-4">
                        <span class="px-3 py-1 bg-primary/10 text-primary rounded-full text-sm">
                            {{ getThemeLabel(selectedQuote.theme) }}
                        </span>
                    </div>

                    <!-- 分享按钮 -->
                    <div class="flex justify-center gap-4 mt-6">
                        <button @click="shareQuote"
                            class="flex items-center gap-2 px-4 py-2 bg-neutral-100 hover:bg-neutral-200 rounded-lg transition-colors">
                            <i class="fa fa-share"></i>
                            <span>分享</span>
                        </button>
                        <button @click="copyQuote"
                            class="flex items-center gap-2 px-4 py-2 bg-primary hover:bg-primary/90 text-white rounded-lg transition-colors">
                            <i class="fa fa-copy"></i>
                            <span>{{ quoteCopied ? '已复制' : '复制' }}</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </PageLayout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import PageLayout from '@/components/layout/PageLayout.vue'
import QuoteCard from '@/components/cards/QuoteCard.vue'
import SectionTitle from '@/components/ui/SectionTitle.vue'
import { quotesData } from '@/data/quotes.js'

// 响应式数据
const selectedTheme = ref('all')
const searchQuery = ref('')
const selectedQuote = ref(null)
const loading = ref(false)
const quoteCopied = ref(false)
const pageSize = 9
const currentPage = ref(1)

// 主题选项
const themes = [
    { label: '全部', value: 'all' },
    { label: '励志', value: 'inspiration' },
    { label: '治愈', value: 'healing' },
    { label: '哲理', value: 'philosophy' },
    { label: '生活', value: 'life' },
    { label: '爱情', value: 'love' }
]

// 扩展的文字数据
const allQuotes = ref([
    ...quotesData,
    // 添加更多数据
    {
        id: 4,
        text: '生活不是等待暴风雨过去，而是学会在雨中跳舞。',
        author: '维维安·格林',
        theme: 'inspiration'
    },
    {
        id: 5,
        text: '真正的快乐不是拥有得多，而是计较得少。',
        author: '佚名',
        theme: 'philosophy'
    },
    {
        id: 6,
        text: '每一个不曾起舞的日子，都是对生命的辜负。',
        author: '尼采',
        theme: 'life'
    },
    {
        id: 7,
        text: '愿你有好运气，如果没有，愿你在不幸中学会慈悲。',
        author: '雷蒙德·卡佛',
        theme: 'healing'
    },
    {
        id: 8,
        text: '爱情不是寻找一个完美的人，而是学会用完美的眼光欣赏不完美的人。',
        author: '佚名',
        theme: 'love'
    }
])

// 计算属性
const filteredQuotes = computed(() => {
    let filtered = allQuotes.value

    // 主题筛选
    if (selectedTheme.value !== 'all') {
        filtered = filtered.filter(quote => quote.theme === selectedTheme.value)
    }

    // 搜索筛选
    if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        filtered = filtered.filter(quote =>
            quote.text.toLowerCase().includes(query) ||
            quote.author.toLowerCase().includes(query)
        )
    }

    return filtered.slice(0, currentPage.value * pageSize)
})

const hasMore = computed(() => {
    const totalFiltered = allQuotes.value.filter(quote => {
        if (selectedTheme.value !== 'all' && quote.theme !== selectedTheme.value) {
            return false
        }
        if (searchQuery.value) {
            const query = searchQuery.value.toLowerCase()
            return quote.text.toLowerCase().includes(query) ||
                quote.author.toLowerCase().includes(query)
        }
        return true
    }).length

    return currentPage.value * pageSize < totalFiltered
})

// 方法
const getThemeLabel = (themeValue) => {
    const theme = themes.find(t => t.value === themeValue)
    return theme ? theme.label : themeValue
}

const loadMore = () => {
    loading.value = true
    setTimeout(() => {
        currentPage.value++
        loading.value = false
    }, 500)
}

const openQuoteDetail = (quote) => {
    selectedQuote.value = quote
    document.body.style.overflow = 'hidden'
}

const closeQuoteDetail = () => {
    selectedQuote.value = null
    quoteCopied.value = false
    document.body.style.overflow = 'auto'
}

const shareQuote = () => {
    if (navigator.share) {
        navigator.share({
            title: 'Life 拾光 - 美好文字',
            text: `"${selectedQuote.value.text}" — ${selectedQuote.value.author}`,
            url: window.location.href
        })
    }
}

const copyQuote = async () => {
    const text = `"${selectedQuote.value.text}" — ${selectedQuote.value.author}`
    try {
        await navigator.clipboard.writeText(text)
        quoteCopied.value = true
        setTimeout(() => {
            quoteCopied.value = false
        }, 2000)
    } catch (err) {
        // 降级方案
        const textArea = document.createElement('textarea')
        textArea.value = text
        document.body.appendChild(textArea)
        textArea.select()
        document.execCommand('copy')
        document.body.removeChild(textArea)
        quoteCopied.value = true
        setTimeout(() => {
            quoteCopied.value = false
        }, 2000)
    }
}

// 重置分页
const resetPagination = () => {
    currentPage.value = 1
}

// 监听器
import { watch } from 'vue'
watch([selectedTheme, searchQuery], resetPagination)
</script>